<?php

namespace app\admin\controller\questionnaire\config;

use app\BaseController;
use app\model\questionnaire\QuestionnaireLabelModel;
use app\model\questionnaire\QuestionnairePaperModel;
use app\model\questionnaire\QuestionnairePaperTopicModel;
use app\model\questionnaire\QuestionnaireTopicAnswerModel;
use app\model\questionnaire\QuestionnaireTopicImgModel;
use app\model\questionnaire\QuestionnaireTopicLabelModel;
use app\model\questionnaire\QuestionnaireTopicModel;
use app\model\questionnaire\QuestionnaireTypeModel;
use think\App;

class Paper extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 问卷分类列表
     * @return bool|string
     */
    public function typeList(): bool|string
    {
        try {
            $where[] = ['status','=',1];
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $QuestionnaireTypeModel = new QuestionnaireTypeModel();
            $data = $QuestionnaireTypeModel->where($where)->order('sort','asc')->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 问卷列表
     * @return bool|string
     */
    public function list(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'pageSize|每页显示数' => 'require',
            ]);
            $where = [];
            if (!empty($param['type_id'])) {
                $where[] = ['type_id', '=', $param['type_id']];
            }
            if (!empty($param['name'])){
                $where[] = ['name', 'like', '%'.$param['name'].'%'];
            }
            if (!empty($param['uid'])) {
                $where[] = ['uid', '=', $param['uid']];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['up_time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['up_time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['up_time', '<=', $param['end_time']];
                }
            }
            if (isset($param['status']) && strlen($param['status'])) {
                $where[] = ['status', '=', $param['status']];
            }
            if (isset($param['total_score']) && strlen($param['total_score'])) {
                $where[] = ['total_score', '=', $param['total_score']];
            }
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $QuestionnairePaperModel = new QuestionnairePaperModel();
            $query = $QuestionnairePaperModel->where($where);
            $data = $query->with(['user'])->paginate($param['pageSize'])->toArray();
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 问卷详情
     * @return bool|string
     */
    public function info(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $QuestionnairePaperModel = new QuestionnairePaperModel();
            $info = $QuestionnairePaperModel->with([
                'paperTopic' => function ($query) {
                    $query->with([
                        'topic' => function ($query) {
                            $query->with(['label','img','answer']);
                        }
                    ]);
                }
            ])->find($id);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            $info['result_read_auth'] = explode(',',$info['result_read_auth']);
            $topic = [];
            foreach ($info['paperTopic'] as $value) {
                $value['topic']['paper_topic_id'] = $value['id'];
                $topic[] = $value['topic'];
            }
            unset($info['paperTopic']);
            $info['topic'] = $topic;
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }


    /**
     * 问卷添加
     * @return bool|string
     */
    public function add(): bool|string
    {
        $QuestionnairePaperModel = new QuestionnairePaperModel();
        $QuestionnairePaperModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'type_id|类型ID' => 'require',
                'name|问卷名称' => 'require',
                'instructions|须知' => 'require',
                'time_limited|限时' => 'require',
                'status|状态' => 'require',
                'result_read_auth|结果权限' => 'require',
                'topic|题目' => 'require',
                'pass_score|及格分数' => 'require'
            ]);
            $param['unit_id'] = $this->userData['unit_id'];
            $param['uid'] = $this->userData['id'];
            $param['time'] = time();
            $param['up_time'] = time();
            if (!empty($param['result_read_auth'])){
                $param['result_read_auth'] = implode(',',$param['result_read_auth']);
            }
            if (!empty($param['topic'])){
                $topicData = [];
                foreach ($param['topic'] as $value) {
                    $topicData[] = [
                        'topic_id' => $value['topic_id'],
                        'num' => $value['num'],
                        'time' => $param['time'],
                    ];
                }
                $param['total_score'] = array_sum(array_column($param['topic'],'score'));
                $param['topic_num'] = count($param['topic']);
                unset($param['topic']);
            }
            $paper_id = $QuestionnairePaperModel->insertGetId($param);
            if (!empty($topicData)){
                foreach ($topicData as &$item){
                    $item['paper_id'] = $paper_id;
                }
                $QuestionnairePaperTopicModel = new QuestionnairePaperTopicModel();
                $QuestionnairePaperTopicModel->insertAll($topicData);
            }
            $QuestionnairePaperModel->commit();
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 问卷编辑
     * @return bool|string
     */
    public function update(): bool|string
    {
        $QuestionnairePaperModel = new QuestionnairePaperModel();
        $QuestionnairePaperModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'name|问卷名称' => 'require',
                'instructions|须知' => 'require',
                'time_limited|限时' => 'require',
                'status|状态' => 'require',
                'result_read_auth|结果权限' => 'require',
                'topic|题目' => 'require',
            ]);
            $info = $QuestionnairePaperModel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if (!empty($param['result_read_auth'])){
                $param['result_read_auth'] = implode(',',$param['result_read_auth']);
            }
            $QuestionnairePaperTopicModel = new QuestionnairePaperTopicModel();
            if (!empty($param['topic_del'])){
                $QuestionnairePaperTopicModel->where('id','in',$param['topic_del'])->update([
                    'is_del' => 1,
                    'del_time' => time(),
                ]);
            }
            if (!empty($param['topic'])){
                $topicData = [];
                foreach ($param['topic'] as $value) {
                    if (empty($value['id'])){
                        unset($value['id']);
                    }
                    $value['paper_id'] = $param['id'];
                    $topicData[] = $value;
                }
                $param['total_score'] = array_sum(array_column($param['topic'],'score'));
                $param['topic_num'] = count($param['topic']);
                unset($param['topic']);
            }
            if (!empty($topicData)){
                $QuestionnairePaperTopicModel->saveAll($topicData);
            }
            $param['up_time'] = time();
            $info->save($param);
            $QuestionnairePaperModel->commit();
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 问卷删除
     * @return bool|string
     */
    public function del(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $QuestionnairePaperModel = new QuestionnairePaperModel();
            if (is_array($id)){
                $QuestionnairePaperModel->where('id','in',$id)->update([
                    'is_del' => 1,
                    'del_time' => time(),
                ]);
            }else{
                $info = $QuestionnairePaperModel->find($id);
                if (!$info) throw new \Exception('参数错误！');
                $info->save([
                    'is_del' => 1,
                    'del_time' => time(),
                ]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 问卷修改状态
     * @return bool|string
     */
    public function status(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'status|状态' => 'require'
            ]);
            $QuestionnairePaperModel = new QuestionnairePaperModel();
            if (is_array($param['id'])){
                $QuestionnairePaperModel->where('id','in',$param['id'])->update([
                    'status' => $param['status']
                ]);
            }else{
                $info = $QuestionnairePaperModel->find($param['id']);
                if (!$info) throw new \Exception('参数错误！');
                $info->save([
                    'status' => $param['status']
                ]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 新增题目到试卷
     * @return bool|string
     */
    public function topicInfoList(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $QuestionnaireTopicModel = new QuestionnaireTopicModel();
            $QuestionnaireTopicImgModel = new QuestionnaireTopicImgModel();
            $QuestionnaireTopicAnswerModel = new QuestionnaireTopicAnswerModel();
            $QuestionnaireTopicLabelModel = new QuestionnaireTopicLabelModel();
            $data = $QuestionnaireTopicModel->where('id','in',$id)->with([
                'label' => function ($query) {
                    $query->with(['labelName']);
                },
                'img',
                'answer'])->select()->toArray();
            $QuestionnaireLabelModel = new QuestionnaireLabelModel();
            foreach ($data as &$item){
                $item['status'] = 0;
                $item['id'] = $QuestionnaireTopicModel->insertGetId([
                    'unit_id' => $this->userData['unit_id'],
                    'uid' => $this->userData['id'],
                    'type' => $item['type'],
                    'score' => $item['score'],
                    'content' => $item['content'],
                    'reference_answer' => $item['reference_answer'],
                    'method' => $item['method'],
                    'method_score' => $item['method_score'],
                    'status' => 0,
                    'up_time' => time(),
                    'time' => time()
                ]);
                foreach ($item['answer'] as &$answer) {
                    $answer['topic_id'] = $item['id'];
                    $answer['id'] = $QuestionnaireTopicAnswerModel->insertGetId([
                        'topic_id' => $item['id'],
                        'name' => $answer['name'],
                        'num' => $answer['num'],
                        'score' => $answer['score'],
                        'status' => $answer['status'],
                        'time' => time()
                    ]);
                    $answer['num'] = 'index'.$answer['num'];
                }
                foreach ($item['img'] as &$img){
                    $img['topic_id'] = $item['id'];
                    $img['id'] = $QuestionnaireTopicImgModel->insertGetId([
                        'topic_id' => $item['id'],
                        'img' => $img['img'],
                        'time' => time()
                    ]);
                }
                foreach ($item['label'] as &$label){
                    $label_id = $QuestionnaireLabelModel->where([
                        ['unit_id','=',$this->userData['unit_id']],
                        ['name','in',$label['name']]
                    ])->value('id');
                    if (!$label_id){
                        $label_id = $QuestionnaireLabelModel->insertGetId([
                            'unit_id' => $this->userData['unit_id'],
                            'name' => $label['name'],
                            'time' => time()
                        ]);
                    }
                    $label['topic_id'] = $item['id'];
                    $label['id'] = $QuestionnaireTopicLabelModel->insertGetId([
                        'topic_id' => $item['id'],
                        'label_id' => $label_id,
                        'time' => time()
                    ]);
                }
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

}